package com.tsj.spzx.user.service.Impl;

import com.alibaba.fastjson.JSON;
import com.tsj.spzx.exception.TsjException;
import com.tsj.spzx.model.dto.h5.UserLoginDto;
import com.tsj.spzx.model.dto.h5.UserRegisterDto;
import com.tsj.spzx.model.entity.user.UserInfo;
import com.tsj.spzx.model.vo.common.ResultCodeEnum;
import com.tsj.spzx.model.vo.h5.UserInfoVo;
import com.tsj.spzx.user.mapper.UserInfoMapper;
import com.tsj.spzx.user.service.UserInfoService;
import com.tsj.spzx.utils.AuthContextThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String USER_REGISTER_KEY = "userMsgCode:";
    private static final String USER_LOGIN_KEY = "userLoginToken:";

    /**
     * 用户注册
     * @param registerDto
     */
    @Override
    public void register(UserRegisterDto registerDto) {
        // 判断参数问题
        if (registerDto.getUsername() == null ||
                registerDto.getPassword() == null ||
                registerDto.getCode() == null ||
                registerDto.getNickName() == null) {
            throw new TsjException(ResultCodeEnum.DATA_ERROR);
        }

        // 首先获得用户名（即手机号）
        String username = registerDto.getUsername();
        // 根据用户名查询验证码
        String code = redisTemplate.opsForValue().get(USER_REGISTER_KEY + username);
        // 判断验证码
        if (!code.equals(registerDto.getCode())){
            throw new TsjException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        // 判断用户名是否存在
        UserInfo userInfo = userInfoMapper.findUserByName(username);
        if (userInfo != null){
            throw new TsjException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        // 没问题 保存数据
        userInfo = new UserInfo();
        userInfo.setAvatar("https://c-ssl.duitang.com/uploads/blog/202402/24/wgSJa9OLI97j3LP.png");
        userInfo.setUsername(username);
        userInfo.setNickName(registerDto.getNickName());
        userInfo.setPassword(DigestUtils.md5DigestAsHex(registerDto.getPassword().getBytes()));
        userInfo.setPhone(username);
        userInfo.setStatus(1);  // 状态
        userInfo.setSex(0);

        userInfoMapper.save(userInfo);

        // 删除redis中存出的验证码
        redisTemplate.delete(USER_REGISTER_KEY + username);
    }

    /**
     * 用户登录
     * @param userLoginDto
     */
    @Override
    public String login(UserLoginDto userLoginDto) {
        // 数据判断
        if (userLoginDto.getUsername() == null || userLoginDto.getPassword() == null) {
            throw new TsjException(ResultCodeEnum.DATA_ERROR);
        }
        // 查询 根据用户名查询用户信息
        UserInfo userInfo = userInfoMapper.findUserByName(userLoginDto.getUsername());
        // 判断用户名是否存在
        if (userInfo == null){
            throw new TsjException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 用户存在就校验密码
        if (!userInfo.getPassword().equals(DigestUtils.md5DigestAsHex(userLoginDto.getPassword().getBytes()))){
            throw new TsjException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 校验用户状态是否正常
        if (userInfo.getStatus() == 0){
            throw new TsjException(ResultCodeEnum.ACCOUNT_STOP);
        }

        // 没有问题的话，生成token，存入redis
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String token = USER_LOGIN_KEY + uuid;
        String userInfoJson = JSON.toJSONString(userInfo);
        redisTemplate.opsForValue().set(token, userInfoJson, 30, TimeUnit.MINUTES);

        return token;
    }

    /**
     * 获取当前登录用户信息
     * @return
     */
    @Override
    public UserInfoVo getCurrentUserInfo(String token) {
        // 判断token是否为空
//        if (token == null){
//            throw new TsjException(ResultCodeEnum.LOGIN_ERROR);
//        }
//
//        // 解析token
//        String userInfoJson = redisTemplate.opsForValue().get(token);
//        if (userInfoJson == null){
//            throw new TsjException(ResultCodeEnum.LOGIN_ERROR);
//        }
//        UserInfo userInfo = JSON.parseObject(userInfoJson, UserInfo.class);

        // 再添加了过滤器，拦截器配合后
        UserInfo userInfo = AuthContextThreadLocalUtil.getUserInfo();
        System.out.println(userInfo + "==================");

        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        return userInfoVo;
    }
}
